package com.star.ms.admin.service.impl.address;

import com.star.ms.admin.dao.impl.user.AddressDAOImpl;
import com.star.ms.admin.dao.impl.user.UserDAOImpl;
import com.star.ms.common.entity.address.Area;
import com.star.ms.common.entity.address.City;
import com.star.ms.common.entity.address.Province;
import com.star.ms.common.entity.user.User;
import com.star.ms.admin.service.address.AddressService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressDAOImpl addressDAO;
    @Autowired
    private UserDAOImpl userDAO;
    public List<Province> getProvinces(){
        return addressDAO.selectProvinces();
    };
    public List<City> getCities(){
        return addressDAO.selectCities();
    };
    public List<Area> getAreas(){
        return addressDAO.selectAreas();
    };

    // 按照上级查询
    public List<City> getCityByProvinceCode(String provinceCode){
        return addressDAO.selectCityByProvinceCode(provinceCode);
    };
    public List<Area> getAreaByCityCode(String cityCode){
        return addressDAO.selectAreaByCityCode(cityCode);
    };

    public Map<String, String> getAddressByCode(String userCode) {
        User user = userDAO.selectByCode(userCode);
        assert user != null;
        String address = user.getAddress();
        if("".equals(address)) return null;
        String[] split = address.split("-");
        assert split.length == 4: "用户的地址不符合[省-市-区-详细地址]的规范";
        Province province = addressDAO.selectProvinceByName(split[0]);
        City city = addressDAO.selectCityByName(split[1]);
        Area area = city == null ? null : addressDAO.selectAreaByNameAndCityCode(split[2], city.getCode());
        Map<String, String> map = new HashMap<>();
        map.put("province", province == null ? "" : province.getCode());
        map.put("city", city == null ? "" : city.getCode());
        map.put("area", area == null ? "" : area.getCode());
        return map;
    }
}
